<template>
  <Card :title="title" :loading="loading">
    <div ref="lineRef" :style="{ height, width }"></div>
  </Card>
</template>
<script lang="ts" setup>
  import { Card } from 'ant-design-vue'
  import { PropType, ref, Ref, watch } from 'vue'
  import { useECharts } from '/@/hooks/web/useECharts'

  const props = defineProps({
    title: String,
    loading: Boolean,
    lineData: Object,
    topColor: {
      type: String,
      default: '#14c8d4',
    },
    bottomColor: {
      type: String,
      default: '#43eec6',
    },
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '300px',
    },
  })

  const lineRef = ref<HTMLDivElement | null>(null)

  const { setOptions, echarts } = useECharts(lineRef as Ref<HTMLDivElement>)

  const lineEchartOptions: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true,
          backgroundColor: '#fff',
        },
      },
    },
    xAxis: {
      data: [0, 0, 0, 0, 0],
      axisLine: {
        lineStyle: {
          color: '#ccc',
        },
      },
    },
    yAxis: {
      min: 0,
      splitLine: { show: false },
      axisLine: {
        lineStyle: {
          color: '#ccc',
        },
      },
      scale: true,
      axisLabel: {
        formatter: function (value) {
          // value大于1000时除以1000并拼接k，小于1000按原格式显示
          if (value >= 1000) {
            value = value / 1000 + 'k'
          } else if (value < 1000) {
            value
          }
          return value
        },
      },
    },
    series: [
      {
        name: props.title,
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          borderRadius: 5,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: props.topColor },
            { offset: 1, color: props.bottomColor },
          ]),
        },
        data: [0, 0, 0, 0, 0],
      },
    ],
  }
  watch(
    () => props.loading,
    () => {
      if (props.loading) {
        return
      }
      setOptions(lineEchartOptions)
    },
    { immediate: true },
  )
  watch(
    () => props.lineData,
    (val) => {
      if (val) {
        setOptions(
          Object.assign(lineEchartOptions, {
            xAxis: { data: val.timeData },
            series: [Object.assign(lineEchartOptions.series[0], { data: val.valueData })],
          }),
        )
      }
    },
    { deep: true },
  )
</script>
